#include "mysql-connect.h"

// 释放 MYSQL 查询得到结果集
void freeQueryResult(MysqlConnect *connect);

struct MysqlConnect {
    MYSQL *mysql;                   // MYSQL 连接实例

    MYSQL_ROW mysql_row;            // 结果集的当前行

    MYSQL_RES *mysql_result;        // SQL 查询得到的结果集
};

MysqlConnect *createConnect(char *ip, char *user, char *password, char *database, int port) {
    MysqlConnect *connect = malloc(sizeof(MysqlConnect));

    // 设置连接实体的初始数据
    connect->mysql_result = NULL;
    connect->mysql = mysql_init(NULL);

    // 设置 MYSQL 的字符串编码
    mysql_set_character_set(connect->mysql, "utf8");

    // 连接 MYSQL 服务器
    connect->mysql = mysql_real_connect(connect->mysql, ip, user, password, database, port, NULL, 0);

#ifdef DEBUG_MYSQL_CONNECT
    printf("Create Mysql Connect Success!\n");
#endif
    return connect;
}

void destroyConnect(MysqlConnect *connect) {
    freeQueryResult(connect);

    mysql_close(connect->mysql);
    connect->mysql = NULL;

    free(connect);

#ifdef DEBUG_MYSQL_CONNECT
    printf("Destory Mysql Connect Success!\n");
#endif
}

bool update(MysqlConnect *connect, char *sql) {
    bool update_result = mysql_query(connect->mysql, sql);

    return update_result;
}

bool query(MysqlConnect *connect, char *sql) {
    // SQL 查询新数据时, 需要先释放之前 SQL 查询得到的结果集
    freeQueryResult(connect);

    // 执行 SQL 查询操作
    bool query_result = mysql_query(connect->mysql, sql);

    // 获取 MYSQL 查询得到的结果集
    connect->mysql_result = mysql_store_result(connect->mysql);

    return query_result;
}

bool next(MysqlConnect *connect) {
    if (connect->mysql_result != NULL) {
        connect->mysql_row = mysql_fetch_row(connect->mysql_result);

        return connect->mysql_row != NULL;
    }

    return false;
}

char *value(MysqlConnect *connect, int index) {
    unsigned int column_count = mysql_num_fields(connect->mysql_result);

    if (index < 0 || column_count <= index) {
        return "";
    }

    return connect->mysql_row[index];
}


bool transaction(MysqlConnect *connect) {
#ifdef DEBUG_MYSQL_CONNECT
    printf("Start Mysql Transaction!\n");
#endif
    return mysql_autocommit(connect->mysql, false);
}

bool commit(MysqlConnect *connect) {
#ifdef DEBUG_MYSQL_CONNECT
    printf("Mysql Transaction Commit!\n");
#endif
    return mysql_commit(connect->mysql);
}

bool rollback(MysqlConnect *pool) {
#ifdef DEBUG_MYSQL_CONNECT
    printf("Mysql Transaction Rollback!\n");
#endif
    return mysql_rollback(pool->mysql);
}

void freeQueryResult(MysqlConnect *connect) {
    if (connect->mysql_result != NULL) {
        mysql_free_result(connect->mysql_result);
    }
    connect->mysql_result = NULL;
}